package com.winit.openapi.gfs.util;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Searchable;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.util.ValidateUtil;


public class GfsCommonUtil {

    public static Searchable buildSearchablePageParams(JSONObject json)
    {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        Searchable search = Searchable.newSearchable();
        // pageParams
        if (isExistValue(json, "pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");

            if (ValidateUtil.isIntNumber(pageParams.getString("pageNo"))) {
                pageNo = pageParams.getInteger("pageNo");
                if (pageNo <= 0) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                }
            } else if (isExistValue(pageParams, "pageNo") && !ValidateUtil.isIntNumber(pageParams.getString("pageNo"))) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageNo");
            }

            if (ValidateUtil.isIntNumber(pageParams.getString("pageSize"))) {
                pageSize = pageParams.getInteger("pageSize");
                if (pageSize <= 0) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                }
            } else if (isExistValue(pageParams, "pageSize")
                       && !ValidateUtil.isIntNumber(pageParams.getString("pageSize"))) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageSize");
            }
        }
        search.setPage(pageNo, pageSize);
        return search;
    }
    
    // 判断非必填字段是否有值
    private static boolean isExistValue(JSONObject jsonObject, String key) {
        if (jsonObject.containsKey(key)) {
            return !"".equals(jsonObject.getString(key).trim());
        }
        return false;
    }
}
